package com.imonsoft.sqm.web.business.ipic_system;

import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.service.basedata.IpicTargetService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.service.business.ipic_system.IPICService;
import com.imonsoft.sqm.vo.business.ipic_system.IPICVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/business/ipic_system/pmcp")
public class PMCPController {
    protected final Log logger = LogFactory.getLog(getClass());
    @Autowired
    private IpicTargetService ipicTargetService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private IPICService ipicService;
    private DecimalFormat decimalFormat=new DecimalFormat(",###");//格式化类

    @RequestMapping("/listTabOneUI.do")
    public void listTabOneUI(ModelMap model) {
        IPICVo ipicVo = new IPICVo();
        ipicVo.setYear(DateUtil.getNowDate().substring(0,4));
        ipicVo.setMonth(DateUtil.getNowDate().substring(5, 7));
        model.put("entity", ipicVo);
    }

    @RequestMapping(value = "/ajaxTabOneList.do", method = RequestMethod.POST)
    public void ajaxTabOneList(HttpServletResponse response, Pager pager, IPICVo ipicVo) {
        DataGrid<IPICVo> dataGrid = new DataGrid<IPICVo>();
        try {
            if(StringUtils.isEmpty(ipicVo.getYear())){
                throw new SystemException("请选择年份！");
            }
            if(StringUtils.isEmpty(ipicVo.getMonth())){
                throw new SystemException("请选择月份！");
            }
            Map<String, Object> searchMap = new HashMap<String, Object>();//查询条件
            searchMap.put("year", ipicVo.getYear());
            searchMap.put("type", ConstantSqm.TYPE_FIELD_CLAIM);
            Map<String,Object> resultMap=new HashMap<String, Object>();//计算结果
            List<IPICVo> ipicVoList = new ArrayList<IPICVo>();

            Supplier supplierSearch = new Supplier();
            supplierSearch.setState(ConstantSqm.STATUS_NORMAL);
            DataGrid<Supplier> supplierDataGrid = supplierService.getDataGrid(supplierSearch, pager);
            List<Supplier> supplierList = supplierDataGrid.getRows();
            for (Supplier supplier : supplierList) {
                IPICVo entity = new IPICVo();
                entity.setSupplierCode(supplier.getCode());
                entity.setSupplierName(supplier.getName());
                searchMap.put("supplierId", supplier.getId());
                searchMap.put("month", ipicVo.getMonth());
                //--月份数据--
                ipicService.calIPICMonthData(searchMap, resultMap);
                entity.setPpm(decimalFormat.format(resultMap.get("ppm")));
                entity.setClaimQuantity(decimalFormat.format(resultMap.get("claimQuantity")));
                entity.setValueP(decimalFormat.format(resultMap.get("valueP")));
                entity.setValueC(decimalFormat.format(resultMap.get("valueC")));
                entity.setIpicMonth(decimalFormat.format(resultMap.get("ipicMonth")));

                //获得当前供应商每个月的ipic值，用于Accumulate，Rolling...提高效率
                Map<Integer,Integer> ipicMonthMap=new HashMap<Integer, Integer>();
                ipicMonthMap.put(Integer.valueOf(ipicVo.getMonth()),(Integer)resultMap.get("ipicMonth"));
                for(int monthTemp=1;monthTemp<Integer.valueOf(ipicVo.getMonth());monthTemp++){
                    searchMap.put("month",StringUtil.paddingZero(monthTemp+"",2));
                    ipicService.calIPICMonthData(searchMap,resultMap);
                    ipicMonthMap.put(monthTemp,(Integer)resultMap.get("ipicMonth"));
                }
                //--累计数据--
                int ipicAccumulate=0;
                for(int monthTemp=1;monthTemp<=Integer.valueOf(ipicVo.getMonth());monthTemp++){
                    ipicAccumulate=ipicAccumulate+ipicMonthMap.get(monthTemp);
                }
                entity.setIpicAccumulate(decimalFormat.format(ipicAccumulate));
                entity.setIpicAverageAccumulate(decimalFormat.format(ipicAccumulate/Integer.valueOf(ipicVo.getMonth())));

                //--滚动数据--
                entity.setIpicRolling(decimalFormat.format(calIPICRollingForTabOne(Integer.valueOf(ipicVo.getMonth()), ipicMonthMap)));

                //得到IPIC目标值
                double ipicTarget=ipicTargetService.getIpicTargetValue(searchMap);
                entity.setTargetIpicAverageYear(decimalFormat.format(ipicTarget));

                //获得投诉数量
                searchMap.put("month", ipicVo.getMonth());
                ipicService.getAccumulateData(searchMap, resultMap);
                entity.setClaimAccumulate(decimalFormat.format(resultMap.get("claimQuantity")));
                ipicVoList.add(entity);
            }
            dataGrid.setRows(ipicVoList);
            dataGrid.setTotal(supplierDataGrid.getTotal());
        } catch (SystemException se) {
            logger.info(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        AjaxUtil.renderJSON(response, JsonUtil.bean2json(dataGrid));
    }

    private int calIPICRollingForTabOne(Integer month, Map<Integer, Integer> ipicMonthMap){
        List<Integer> monthList=new ArrayList<Integer>();
        if(month<=2){
            for(int monthTemp=1;monthTemp<=month;monthTemp++){
                monthList.add(monthTemp);
            }
        }else{
            for(int monthTemp=month-2;monthTemp<=month;monthTemp++){
                monthList.add(monthTemp);
            }
        }
        int ipicRolling=0;
        for(Integer monthTemp:monthList){
            ipicRolling=ipicRolling+ipicMonthMap.get(monthTemp);
        }
        return ipicRolling;
    }




    @RequestMapping("/listTabTwoUI.do")
    public void listTabTwoUI(ModelMap model) {
        IPICVo ipicVo = new IPICVo();
        ipicVo.setYear(DateUtil.getNowDate().substring(0,4));
        model.put("entity", ipicVo);
    }
    @RequestMapping(value = "/ajaxTabTwoList.do", method = RequestMethod.POST)
    public void ajaxTabTwoList(HttpServletResponse response, IPICVo ipicVo) {
        DataGrid<IPICVo> dataGrid = new DataGrid<IPICVo>();
        try {
            if(null==ipicVo.getSupplierId()){
                throw new SystemException("请选择供应商！");
            }
            if(StringUtils.isEmpty(ipicVo.getYear())){
                throw new SystemException("请选择年份！");
            }
            Map<String, Object> searchMap = new HashMap<String, Object>();//查询条件
            searchMap.put("supplierId", ipicVo.getSupplierId());
            searchMap.put("year", ipicVo.getYear());
            searchMap.put("type", ConstantSqm.TYPE_FIELD_CLAIM);
            Map<String,Object> resultMap=new HashMap<String, Object>();//计算结果
            List<IPICVo> ipicVoList = new ArrayList<IPICVo>();
            //获得当前供应商每个月的ipic值，用于Accumulate，Rolling...提高效率
            Map<Integer,Integer> ipicMonthMap=new HashMap<Integer, Integer>();

            for(int monthTemp=1;monthTemp<=12;monthTemp++){
                IPICVo entity = new IPICVo();
                entity.setMonth(StringUtil.paddingZero("" + monthTemp, 2));
                searchMap.put("month", StringUtil.paddingZero(""+monthTemp,2));

                //--月份数据--
                ipicService.calIPICMonthData(searchMap, resultMap);
                entity.setPpm(decimalFormat.format(resultMap.get("ppm")));
                entity.setClaimQuantity(decimalFormat.format(resultMap.get("claimQuantity")));
                entity.setValueP(decimalFormat.format(resultMap.get("valueP")));
                entity.setValueC(decimalFormat.format(resultMap.get("valueC")));
                entity.setIpicMonth(decimalFormat.format(resultMap.get("ipicMonth")));

                ipicMonthMap.put(monthTemp,(Integer)resultMap.get("ipicMonth"));
                //--累计数据--
                int ipicAccumulate=0;
                for(int temp=1;temp<=monthTemp;temp++){
                    ipicAccumulate=ipicAccumulate+ipicMonthMap.get(temp);
                }
                entity.setIpicAccumulate(decimalFormat.format(ipicAccumulate));
                entity.setIpicAverageAccumulate(decimalFormat.format(ipicAccumulate/monthTemp));

                //--滚动数据--
                int ipicRolling=0;
                if(monthTemp==1){
                    ipicRolling=ipicMonthMap.get(1);
                }else if(monthTemp==2){
                    ipicRolling=ipicMonthMap.get(1)+ipicMonthMap.get(2);
                }else{
                    for(int temp=monthTemp-2;temp<=monthTemp;temp++){
                        ipicRolling=ipicRolling+ipicMonthMap.get(temp);
                    }
                }
                entity.setIpicRolling(decimalFormat.format(ipicRolling));
                //得到IPIC目标值
                double ipicTarget=ipicTargetService.getIpicTargetValue(searchMap);
                entity.setTargetIpicAverageYear(decimalFormat.format(ipicTarget));
                //获得投诉数量
                ipicService.getAccumulateData(searchMap,resultMap);
                entity.setClaimAccumulate(decimalFormat.format(resultMap.get("claimQuantity")));
                ipicVoList.add(entity);
            }
            dataGrid.setRows(ipicVoList);
            dataGrid.setTotal(12);
        } catch (SystemException se) {
            logger.info(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        AjaxUtil.renderJSON(response, JsonUtil.bean2json(dataGrid));
    }

    @RequestMapping("/tabUI.do")
    public void tabUI() {
    }
}
